<template>
	<!-- 绑定手机号码弹框 -->
	<uni-popup ref="PhonePadPopup" type="bottom" :is-mask-click="false">
		<PhonePad @close="closePhonePad" />
	</uni-popup>
	<!-- 加注机状态； -->
	<FillStatus @fillStatus="fillStatus" ref="filling"></FillStatus>
	<!-- 账户充值到账 -->
	<ReceivedPop @changes="changes()"></ReceivedPop>
</template>

<script setup lang="ts">
	import { ref } from 'vue';
	import ReceivedPop from '@c/pobulic/Received.vue';
	import { orderJ } from '@/gql/filling';
	import { toPublish } from '@mqtt';
	import FillStatus from '@c/canCode/fillingStatus.vue';
	import { onUnload } from '@dcloudio/uni-app';
	import { showLoading, showToast, errorToast } from '@/utils/prompt';
	import { onLoad } from '@dcloudio/uni-app';
	import PhonePad from '@c/common/PhonePad.vue';
	import { useUserStore } from '@/stores/user';
	import { getDriverID } from '@/stores/driverID';
	/**
	 * @component
	 * @desc 底部支付
	 * @property {Number} driver_id 用户ID
	 * @property {Object} userInfo 用户信息
	 * @property {Null} filling 加注机状态组件值
	 * @property {Boolean} repeat 其他加注防重复点击
	 * @property {String} payment 支付方式1微信2余额
	 * @property {String} orderids 加注订单ID
	 * @property {Number} time 支付反馈倒计时
	 * @property {Null} TimerTask 定义的倒计时
	 * @property {Boolean} ComeBackOrder 是否返回支付消息
	 * @property {Null} PhonePadPopup 保定手机号码弹框
	 * @property {String} type 身份判断  team车友团 takeOut外卖单
	 * @property {Number} num 支付总价
	 * @property {String} state 身份判断  investors散户 team车友团  shop店铺机
	 * @property {Number} from_id 代付款人ID
	 * @property {Number} union_id 联营商Id
	 * @property {Number} teamId 团iD
	 */
	const driver_id = getDriverID();
	const userInfo = useUserStore();
	const filling = ref(null);
	const repeat = ref(false);
	const payment = ref('');
	const orderids = ref('');

	let time = 0;
	let TimerTask = null; //定时器

	let ComeBackOrder = false; //是否返回的订单ID
	const PhonePadPopup = ref(null); //保定手机号码弹框

	const amonut = ref() //加注量
	const univalent = ref() //单价
	const type = ref('')

	const props = defineProps({
		num: {
			type: Number,
			default: 0,
		},
		state: {
			type: String,
			default: '',
		},
		from_id: {
			type: Number,
			default: 0,
		},
		union_id: {
			type: Number,
			default: 0,
		},
		teamId: {
			type: String,
			default: '0',
		},
		fillamount: {
			type: Number,
		},
		code: {
			type: String,
			default: '0371',
		}
	});
	onLoad(() => {
		if (!userInfo.avatar) {
			userInfo.getUserInfo();
		}
	});
	const emit = defineEmits(['takeOutSub', 'getdrivers']);
	//打开绑定手机弹框
	function openPhonePad() {
		PhonePadPopup.value.open();
	}
	//关闭绑定手机弹框
	function closePhonePad() {
		PhonePadPopup.value.close();
	}
	function changes() {
		emit('getdrivers', 15)
		return
	}
	/**
	 * 提交获取
	 * @param {String} state 加注方式1微信2余额
	 * @param {Number} amount 加注量
	 * @param {Number} price 加注金额
	 */
	function submit(state : string, amount : number, price : number) {
		payment.value = state === 'wechat' ? '1' : '2';
		amonut.value = amount
		type.value = state
		univalent.value = price
		if (props.fillamount == 0 && state !== 'shiwu') {
			emit('getdrivers', 15)
			return
		}
		showLoading();
		const payload = {
			query: orderJ,
			variables: {
				driver_id,
			},
		};
		toPublish('ql/driver/doFillingOrderId', payload, (obj : any) => {
			const { do_filling_order_id } = obj.data;
			if (do_filling_order_id.order_id) {
				// 提示文字
				PromptText('您有一个订单正在进行中', do_filling_order_id.order_id);
			} else {
				if (!props.from_id && payment.value === '2'&& state !== 'shiwu') {
					errorToast('暂无老板授权账户');
					return;
				}
				if (props.state == 'takeOut') {
					//takeOut 外卖单加注需绑定手机号码
					if (!userInfo.mobile) {
						showToast('请绑定您的手机号码');
						openPhonePad();
						return;
					}
					emit('takeOutSub', { num: payment.value });
				} else {
					// 提交检测加注机状态
					filling.value.FillingMachine();
					// 订阅加注机返回信息
					filling.value.ComeBackFilling();
				}
				// FillingStatus()
			}
		});
	}
	/**
	 * 加注机状态
	 * @param {String} num 加注状态返回值
	 */
	function fillStatus(num : string) {
		if (num == 'task_ready_ack' || num == 'circle_upload_ack') {
			if (props.state == 'readyMoney') {
				emit('takeOutSub', payment.value);
			} else if (type.value === 'shiwu') {
				inventory()
			} else {
				FillingStatus();
			}
		} else {
			showToast('当前加注机繁忙 请稍后重试');
			return;
		}
	}
	/**
	 * 加注
	 * @property {Number} fill_id 加注机ID
	 * @property {String} platform 支付平台 mini小程序/mp公众号
	 * @property {String} paytype 支付方式
	 * @property {String} pay_type 支付方式
	 * @property {String} count 加注量
	 * @property {String} amount 加注量
	 * @property {Nuber} price 支付金额
	 * @property {Number} from_driver_id 待付款人ID
	 */
	function FillingStatus() {
		if (repeat.value) {
			return;
		}
		repeat.value = true;
		const fill_id = uni.getStorageSync('fillingID');
		const platform = 'mp';
		const paytype = payment.value == '1' ? 'wechat' : 'money';
		const pay_type = payment.value === '1' ? 'mp' : 'money';
		const count = amonut.value;
		const amount = amonut.value;
		const price = univalent.value;
		const from_driver_id = payment.value === '1' ? '' : props.from_id;
		if (payment.value === '2' && !props.from_id) {
			showToast('当前余额不足');
			return;
		}
		showLoading('正在提交');
		switch (props.state) {
			case 'investors':
				const pearm = {
					order_type: 'filling',
					type: 'quota',
					driver_id,
					latitude: 0,
					longitude: 0,
					price: props.num,
					count: count ? count : amount,
					fill_id,
					union_id: props.union_id,
					platform,
					paytype,
				};
				delTimerTask();
				//定时器获取数据信息
				TimerLater('FillingStatus');
				toPublish('order_filling/addOrder', pearm, SubmitResult);
				break;
			case 'team':
				const pearm1 = {
					driver_id,
					money: props.num,
					amount,
					price,
					fill_id,
					platform,
					paytype,
					team_id: Number(props.teamId),
					from_driver_id,
					pay_type,
				};
				delTimerTask();
				//定时器获取数据信息
				TimerLater('submit');
				toPublish('team/addOrder', pearm1, SubmitResult);
				break;
			case 'shop':
				const pearm2 = {
					driver_id,
					money: props.num,
					amount,
					price,
					fill_id,
					platform,
					paytype,
					shop_id: Number(props.teamId),
					from_driver_id,
					pay_type,
				};
				delTimerTask();
				//定时器获取数据信息
				TimerLater('submit');
				toPublish('shop/addOrder', pearm2, SubmitResult);
				break;
			case 'KeyFill':
				const pearm3 = {
					order_type: 'filling',
					type: 'quota',
					driver_id,
					latitude: 0,
					longitude: 0,
					fill_price: price,
					price: props.num,
					count: count ? count : amount,
					money_id: from_driver_id,
					fill_id,
					union_id: props.union_id,
					platform,
					pay_type,
				};
				delTimerTask();
				//定时器获取数据信息
				TimerLater('FillingStatus');
				toPublish('order_filling/addCommonOrder', pearm3, SubmitResult);
				break;
		}
	}
	/**
	 * 返回加注信息
	 * @property {Object} obj 返回提交加注信息
	 */
	function SubmitResult(obj : any) {
		const { code, msg, data } = obj;
		ComeBackOrder = true;
		delTimerTask();
		if (code === 1) {
			uni.hideLoading();
			switch (props.state) {
				case 'investors':
					editOrder(data.order_id);
					break;
				case 'team':
					editResults(data.order_id);
					break;
				case 'shop':
					editResults(data.order_id);
					break;
				case 'KeyFill':
					editResults(data.order_id);
					break;
			}
		} else {
			Paymentfailed(msg);
			return;
		}
	}
	/**
	 * 提交加注信息
	 * @param {String} order_id 订单ID
	 * @param {String} pay_type 支付方式 余额/微信
	 * @param {Number} from_driver_id 待付款人ID
	 */
	function editOrder(order_id : string) {
		showLoading('正在提交');
		const pay_type = payment.value === '1' ? 'mp' : 'money';
		const from_driver_id = payment.value === '1' ? '' : props.from_id;
		if (payment.value === '2' && !props.from_id) {
			showToast('当前余额不足');
			return;
		}
		const payload = {
			driver_id,
			order_id,
			pay_type,
			cart_code: '',
			from_driver_id,
			order_type: 'filling',
		};
		//定时器获取数据信息
		delTimerTask();
		TimerLater('editOrder', order_id);
		toPublish('order_filling/editOrder', payload, (obj : any) => {
			const { code, msg, data } = obj;
			if (code === 1) {
				editResults(data.order_id);
				delTimerTask();
			} else {
				Paymentfailed(msg);
			}
		});
	}
	/**
	 * @param {Object} order_id 订单ID
	 * @param {Number} UnboundNum 支付方式
	 */
	function editResults(order_id : string) {
		const UnboundNum = payment.value;
		orderids.value = order_id;
		repeat.value = false;
		switch (UnboundNum) {
			case '1':
				// 微信支付
				weachPay(order_id);
				break;
			case '2':
				// 余额支付
				payFors(order_id);
				break;
		}
	}

	/**
	 * 微信支付
	 * @param {Object} num 订单ID
	 * @param {Number} driver_id 加注人ID
	 */
	function weachPay(num : any) {
		showLoading('正在提交');
		const payload = {
			driver_id,
			order_type: 'filling',
			order_id: num,
			type: 'wechat',
			method: 'mp',
		};
		delTimerTask();
		//定时器获取数据信息
		TimerLater('weachPay', num);
		toPublish('order_filling/payWechat', payload, (obj : any) => {
			delTimerTask();
			ComeBackOrder = true;
			const { code, msg, data } = obj;
			if (code === 1) {
				weach(data);
			} else {
				Paymentfailed(msg);
				return;
			}
		});
	}
	/**
	 * 微信支付
	 */
	function weach(num : any) {
		showLoading();
		WeixinJSBridge.invoke('getBrandWCPayRequest', num, function (res) {
			switch (res.err_msg) {
				case 'get_brand_wcpay_request:ok':
					showToast('支付成功');
					showLoading()
					setTimeout(() => {
						if (props.state == 'takeOut') {
							uni.setStorageSync('active', 1);
							uni.redirectTo({
								url: '/pages/order/myOrder?index=1',
							});
						} else {
							uni.redirectTo({
								url: '/pages/canCode/canState?id=' + orderids.value,
							});
						}
					}, 1500);
					break;
				case 'get_brand_wcpay_request:cancel':
					Paymentfailed('取消支付 请稍后重试');
					break;
				case 'get_brand_wcpay_request:fail':
					Paymentfailed('支付失败 请稍后重试');
					break;
			}
		});
	}
	/**
	 * 余额支付
	 * @param {String} order_id 订单ID
	 */
	function payFors(num : string) {
		showLoading('正在提交');
		const payload = {
			driver_id,
			order_id: num,
		};
		delTimerTask();
		//定时器获取数据信息
		TimerLater('payFors', num);
		const tipc = type.value === 'fenbo' ? 'order_filling/payFenbo' : type.value === 'fleet' ? 'order_filling/payFleet' : 'order_filling/payMoney'
		toPublish(tipc, payload, (obj : any) => {
			ComeBackOrder = true;
			const { code, msg, data } = obj;
			delTimerTask();
			if (code === 1) {
				showLoading()
				showToast('支付成功');
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/canCode/canState?id=' + data.order_id,
					});
				}, 1500);
			} else {
				Paymentfailed(msg);
				return;
			}
		});
	}
	/**
	 * 定时器获取数据确保信息送达
	 */
	function TimerLater(name, num ?) {
		// 每300毫秒查看是否请求走完
		TimerTask = setInterval(() => {
			time++;
			if (time < 11 && !ComeBackOrder) {
				switch (name) {
					case 'FillingStatus':
						FillingStatus();
						break;
					case 'editOrder':
						editOrder(num);
						break;
					case 'weachPay':
						weachPay(num);
						break;
					case 'payFors':
						payFors(num);
						break;
				}
			} else if (time > 10 && !ComeBackOrder) {
				Paymentfailed('支付失败 请稍后重试');
				return;
			}
		}, 1000);
	}
	//实物库存支付
	function inventory() {
		showLoading('正在提交');
		const payload = {
			driver_id,
			code: props.code,
			fill_id: uni.getStorageSync('fillingID'),
			platform: 'wechat',
		};
		toPublish('driver/addOrderAmount', payload, (obj : any) => {
			const { code, msg, data } = obj;
			if (code === 1) {
				submitOrder(data.order_id)
			} else {
				errorToast(msg);
			}
		});
	}
	function submitOrder(order_id : number) {
		showLoading('正在提交');
		const payload = {
			driver_id,
			order_id
		};
		toPublish('order_filling/payAmount', payload, (obj : any) => {
			const { code, msg, data } = obj;
			if (code === 1) {
				showToast('支付成功');
				setTimeout(() => {
					uni.redirectTo({
						url: '/pages/canCode/canState?id=' + data.order_id,
					});
				}, 1500);
			} else {
				errorToast(msg);
			}
		});
	}
	/**
	 * 清除定时器
	 */
	function delTimerTask() {
		if (TimerTask) {
			clearInterval(TimerTask);
			TimerTask = null;
		}
	}
	/**
	 * 支付失败
	 */
	function Paymentfailed(msg) {
		uni.hideLoading();
		time = 0;
		delTimerTask();
		repeat.value = false;
		setTimeout(function () {
			errorToast(msg);
		}, 100);
	}

	/**
	 * 提示文字
	 */
	function PromptText(text : string, num) {
		showToast(text);
		setTimeout(() => {
			uni.redirectTo({
				url: '/pages/canCode/canState?id=' + num + '&type=1',
			});
		}, 600);
	}

	/**
	 * 外卖单微信支付
	 */
	function takeOutWeatch(num : string) {
		showLoading('正在提交');
		const payload = {
			order_id: num,
		};
		toPublish('take/payWechat', payload, (obj : any) => {
			ComeBackOrder = true;
			const { code, msg, data } = obj;
			if (code === 1) {
				weach(data);
			} else {
				Paymentfailed(msg);
				return;
			}
		});
	}
	/**
	 * 外卖单余额支付
	 */
	function takeMoney(num : string) {
		showLoading('正在提交');
		const payload = {
			order_id: num,
		};
		toPublish('take/payMoney', payload, (obj : any) => {
			const { code, msg } = obj;
			if (code === 1) {
				showToast('支付成功');
				setTimeout(() => {
					uni.setStorageSync('active', 1);
					uni.redirectTo({
						url: '/pages/order/myOrder',
					});
				}, 1500);
			} else {
				Paymentfailed(msg);
				return;
			}
		});
	}
	defineExpose({
		takeOutWeatch,
		takeMoney,
		submit,
	});
	onUnload(() => {
		time = 0;
		delTimerTask();
	});
</script>

<style lang="less">
	.amount {
		width: 100%;
		color: #1b91ff;
		font-size: 30rpx;
		display: flex;
		justify-content: center;
		align-items: center;

		view:nth-of-type(2) {
			margin-left: 15rpx;

			text:nth-of-type(2) {
				font-size: 48rpx;
			}
		}
	}

	.payBtn {
		width: 48.5%;
		background-color: #eee;
		border-radius: 5px;
		padding: 15rpx 15rpx 10rpx;
		box-sizing: border-box;
		margin-top: 20rpx;
		box-shadow: 0px 4px 4px 1px rgba(179, 179, 179, 0.25);

		.UnitPrice {
			color: #666;
			font-size: 24rpx;
			font-weight: 400;

			view:nth-of-type(1) {
				width: 80rpx;
				text-align: justify;
				text-justify: distribute-all-lines;
				text-align-last: justify;
				margin-right: 20rpx;
			}

			view:nth-of-type(2) {
				text:nth-of-type(1) {
					font-size: 28rpx;
				}
			}
		}

		.botCode {
			width: 100%;
			padding: 0px 20rpx;
			box-sizing: border-box;
			height: 88rpx;
			border-radius: 5px;
			margin-top: 15rpx;
			color: #fff;

			image {
				width: 38rpx;
				height: 34rpx;
				margin-right: 15rpx;
			}
		}
	}
</style>